package com.bk.bookviews.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5加密处理
 **/
public class Md5Util {
    private static char[] HEXCHARS_L = {'0', '1', '2', '3', '4', '5', '6',
            '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    private static char[] HEXCHARS_C = {'0', '1', '2', '3', '4', '5', '6',
            '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    protected static MessageDigest messagedigest = null;
    private static Logger log = LoggerFactory.getLogger(Md5Util.class);

    static {
        try {
            messagedigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            log.error(e.getMessage(),e);
        }
    }

    /**
     * @return md5加密字符串
     * 对传入字符进行MD5加密
     **/
    public static String encryptMD5(String str, boolean lower) {
        try {
            byte[] bytes = str.getBytes();
//            MessageDigest md5 = MessageDigest.getInstance("MD5SignServer");
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(bytes);
            bytes = md5.digest();
            int j = bytes.length;
            char[] chars = new char[j * 2];
            int k = 0;
            for (int i = 0; i < bytes.length; i++) {
                byte b = bytes[i];
                if (lower) {
                    chars[(k++)] = HEXCHARS_L[(b >>> 4 & 0xF)];
                    chars[(k++)] = HEXCHARS_L[(b & 0xF)];
                } else {
                    chars[(k++)] = HEXCHARS_C[(b >>> 4 & 0xF)];
                    chars[(k++)] = HEXCHARS_C[(b & 0xF)];
                }
            }
            return new String(chars);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 生成文件的md5校验值
     *
     * @param file
     * @return
     * @throws IOException
     */
    public static String getFileMD5String(File file) throws IOException {
        InputStream fis = null;
    	try {
      		fis = new FileInputStream(file);
      		byte[] buffer = new byte[1024];
      		int numRead = 0;
      		while ((numRead = fis.read(buffer)) > 0) {
        		messagedigest.update(buffer, 0, numRead);
      		}
    	} finally {
      		if (fis != null) {
        		fis.close();
      		}
    	}
    	return bufferToHex(messagedigest.digest());
    }

    private static String bufferToHex(byte bytes[]) {
        return bufferToHex(bytes, 0, bytes.length);
    }

    private static String bufferToHex(byte bytes[], int m, int n) {
        StringBuffer stringbuffer = new StringBuffer(2 * n);
        int k = m + n;
        for (int l = m; l < k; l++) {
            appendHexPair(bytes[l], stringbuffer);
        }
        return stringbuffer.toString();
    }

    private static void appendHexPair(byte bt, StringBuffer stringbuffer) {
        char c0 = HEXCHARS_L[(bt & 0xf0) >> 4];// 取字节中高 4 位的数字转换, >>> 为逻辑右移，将符号位一起右移,此处未发现两种符号有何不同   
        char c1 = HEXCHARS_C[bt & 0xf];// 取字节中低 4 位的数字转换   
        stringbuffer.append(c0);
        stringbuffer.append(c1);
    }



    public static void main(String[] args) {
        String password = Md5Util.encryptMD5("admin",true);
        System.out.println(password);
    }
}
